from models import db, Technician, RepairOrder
from common.response import APIResponse
import bcrypt

class TechnicianService:
    @staticmethod
    def login_technician(phone, password):
        # 师傅登录
        technician = Technician.query.filter_by(phone=phone).first()
        if not bcrypt.checkpw(password.encode('utf-8'), technician.password.encode('utf-8')):
            return APIResponse.fail('Incorrect password', 20002)
        return APIResponse.success(technician.to_dict(), 'Login successful')

    @staticmethod
    def get_technician_by_id(technician_id):
        technician = Technician.query.filter_by(id=technician_id).first()
        if not technician:
            return APIResponse.not_found('Technician not found')
        return APIResponse.success(technician.to_dict())

    @staticmethod
    def get_all_technicians(args):
        # 要支持分页查询
        page = args.get('page', 1, type=int)
        per_page = args.get('pageSize', 10, type=int)
        # 根据姓名查询
        name = args.get('name')
        if name:
            technicians = Technician.query.filter(Technician.name.like(f'%{name}%')).paginate(page=page, per_page=per_page, error_out=False)
        else:
            technicians = Technician.query.paginate(page=page, per_page=per_page, error_out=False)
        return APIResponse.success({
            'total': technicians.total,
            'items': [technician.to_dict() for technician in technicians.items]
        })

    @staticmethod
    def get_technicians_by_name(name):
        technicians = Technician.query.filter(Technician.name.like(f'%{name}%')).all()
        return APIResponse.success([technician.to_dict() for technician in technicians])

    @staticmethod
    def create_technician(data):
        # 验证必填字段
        required_fields = ['name', 'phone']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')

        # 检查电话是否已存在
        if Technician.query.filter_by(phone=data['phone']).first():
            return APIResponse.fail('Phone number already exists', 10002)

        # 检查身份证号是否已存在
        if 'id_card' in data and data['id_card']:
            if Technician.query.filter_by(id_card=data['id_card']).first():
                return APIResponse.fail('ID card already exists', 10003)

        # 创建新技师
        new_technician = Technician(
            name=data['name'],
            phone=data['phone'],
            id_card=data.get('id_card'),
            gender=data.get('gender', 0),
            age=data.get('age'),
            work_years=data.get('work_years')
        )

        try:
            new_technician.save()
            return APIResponse.success(new_technician.to_dict(), 'Technician created successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10004)

    @staticmethod
    def update_technician(technician_id, data):
        technician = Technician.query.filter_by(id=technician_id).first()
        if not technician:
            return APIResponse.not_found('Technician not found')

        # 检查更新的电话是否已存在
        if 'phone' in data and data['phone'] != technician.phone:
            if Technician.query.filter_by(phone=data['phone']).first():
                return APIResponse.fail('Phone number already exists', 10002)
            technician.phone = data['phone']

        # 检查更新的身份证号是否已存在
        if 'id_card' in data and data['id_card'] != technician.id_card:
            if data['id_card'] and Technician.query.filter_by(id_card=data['id_card']).first():
                return APIResponse.fail('ID card already exists', 10003)
            technician.id_card = data['id_card']

        # 更新其他字段
        if 'name' in data:
            technician.name = data['name']
        if 'gender' in data:
            technician.gender = 1 if data['gender'] == '男' else 2 if data['gender'] == '女' else 0
        if 'age' in data:
            technician.age = data['age']
        if 'work_years' in data:
            technician.work_years = data['work_years']
        if 'head' in data:
            technician.head = data['head']
        if 'password' in data:
            password_hash = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())
            technician.password = password_hash

        try:
            technician.save()
            return APIResponse.success(technician.to_dict(), 'Technician updated successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10004)

    @staticmethod
    def delete_technician(technician_id):
        technician = Technician.query.filter_by(id=technician_id).first()
        if not technician:
            return APIResponse.not_found('Technician not found')

        try:
            technician.delete()
            return APIResponse.success(None, 'Technician deleted successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10004)